import pinyin from 'pinyin';

const pinyinUtils = {
  /**
   * 汉字转拼音
   * @param han 汉字
   * @returns str string
   */
  han2pinyin: (han: string) => {
    return pinyin(han, {
      style: pinyin.STYLE_NORMAL,
    }).join('');
  },
  /**
   * 筛选数据
   * @param keyword 关键字
   * @param field 要搜索的字段-默认 pinyin，如果是搜索纯字母，则强制搜索pinyin字段
   * @param dataSource 数据源
   */
  search: (keyword: string, dataSource: any[], field = 'pinyin') => {
    const value = keyword.trim();
    let data: any[] = [];
    if (value) {
      // 中英文搜索
      const isletter = /^[\u4e00-\u9fa5_a-zA-Z]+$/.test(value);
      if (isletter) {
        data = dataSource.filter((item) => {
          const _field = /^[_a-zA-Z]+$/.test(value) ? item.pinyin : item[field] || field;
          if (value.length > _field.length) {
            const a = new RegExp(_field, 'gim');
            return a.test(value);
          } else {
            const b = new RegExp(value, 'gim');
            return b.test(_field);
          }
        });
      } else {
        data = dataSource.filter((item) => {
          const _field = item[field] || field;
          return value.length > _field.length ? value.includes(_field) : _field.includes(value);
        });
      }
      return data;
    } else {
      return [];
    }
  },
};

export default pinyinUtils;
